//
//  LoadPokeManRequest.swift
//  PokeMaster
//
//  Created by 李腾芳 on 2022/1/13.
//  Copyright © 2022 OneV's Den. All rights reserved.
//

import Foundation
import Combine

struct LoadPokeManRequest {
    let id: String
    
    func pokeManPublisher() -> AnyPublisher<Pokemon, Error> {
        URLSession.shared
            .dataTaskPublisher(for: URLRequest(url: URL(string: "https://pokeapi.co/api/v2/pokemon/\(id)")!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData ))
          //  .dataTaskPublisher(for: URL(string: "https://pokeapi.co/api/v2/pokemon/\(id)")!)
            .map {
             //   print($0.response)
               return  $0.data
                
            }
            .decode(type: Pokemon.self, decoder: appDecoder)
            .eraseToAnyPublisher()
    }
    
    func species(_ pokemon: Pokemon) -> AnyPublisher<(Pokemon, PokemonSpecies), Error> {
        URLSession.shared
            .dataTaskPublisher(for: pokemon.species.url)
            .map { $0.data }
            .decode(type: PokemonSpecies.self, decoder: appDecoder)
            .map { (pokemon, $0)}
            .eraseToAnyPublisher()
    }
    
    var publisher: AnyPublisher<(PokemonViewModel), AppError> {
        pokeManPublisher()
            .flatMap { species($0) }
            .mapError { error in AppError.networkingError(error) }
            .receive(on: DispatchQueue.main)
            .map { PokemonViewModel(pokemon: $0.0, species: $0.1) }
            .eraseToAnyPublisher()
    }
    
    static func all() -> AnyPublisher<[PokemonViewModel], AppError> {
        (1...30).map {
            LoadPokeManRequest(id: "\($0)").publisher
        }
        .zipAll
    }
}
